import os
import shutil

FILE_SEPARATOR = os.sep
PARENT_DIR = os.pardir

def makeDir(dir):
    if not(os.path.isdir(dir)):
        print "Creating " + dir 
        os.mkdir(dir)
    
        # non recursively
def copyDir(parentDir, dirname):
    dir = os.path.basename(dirname)
    dir = parentDir + FILE_SEPARATOR + dir
    makeDir(dir)
    
    files = os.listdir(dirname)
    for file in files:
        if not(os.path.isfile(dirname + FILE_SEPARATOR + file)):
            continue
        if file.upper() == ".SVN":
            continue
        print "Copying " + dir + FILE_SEPARATOR + file
        shutil.copyfile(dirname + FILE_SEPARATOR + file, dir + FILE_SEPARATOR + file)

def install(installDir):    
    from pyeasyaccept.commom.Configuration import Configuration
            
    Configuration.getInstance().setInstallDir(installDir)
    rootDir = Configuration.getInstance().INSTALL_DIR
    
    if os.path.isdir(rootDir):
        print "Removing tree " + rootDir 
        shutil.rmtree(rootDir)
     
    makeDir(rootDir)    
    
    iconsDir = rootDir+FILE_SEPARATOR+"icons"    
    currentIconsDir = os.getcwd() + FILE_SEPARATOR + "icons"
    
    copyDir(rootDir, currentIconsDir)
    shutil.copy("src" + FILE_SEPARATOR + "pyeasyaccept" + FILE_SEPARATOR + "PythonEasyAccept.py" , rootDir)
    
def chooseDestinationDir():
    validDir = False
    installDir = None
    while not validDir:
        installDir = raw_input("Type the destination location to install Python EasyAccept:")
        if not os.path.isdir(installDir):
            print "Invalid directory. Please, type a valid destination location."
            print
        else:
            validDir = True
    return installDir

def setWinRegDestDir(installDir):
    import _winreg
    explorer = _winreg.CreateKey(_winreg.HKEY_LOCAL_MACHINE, "Software" + FILE_SEPARATOR + "PythonEasyAccept")
    _winreg.SetValue(explorer, "Software" + FILE_SEPARATOR + "PythonEasyAccept", _winreg.REG_SZ, installDir)
    _winreg.FlushKey(explorer)
    print _winreg.QueryValue(explorer, "Software" + FILE_SEPARATOR + "PythonEasyAccept")
    _winreg.CloseKey(explorer)
    
if __name__ == '__main__':
    
    if os.name == "nt":
        destDir = os.getenv("USERPROFILE") + FILE_SEPARATOR + "PythonEasyAccept"
        setWinRegDestDir(destDir)
    else:
         destDir = os.getenv("HOME") + FILE_SEPARATOR + "PythonEasyAccept"

    print "Installing Python EasyAccept..."
    print
    
    os.system("python setup.py install")
    install(destDir)
    
    print "Python EasyAccept was successful installed in", destDir
    
    
    